package com.sixfoot.facade.role;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sixfoot.dao.PermissionRepository;
import com.sixfoot.domain.Permission;
import com.sixfoot.domain.Role;
import com.sixfoot.foundation.mapping.adapter.AbstractDtoAdapter;

@Component
public class RoleAdapter extends AbstractDtoAdapter<Role, RoleDto, RoleInputArgs> {
	@Autowired
	private PermissionRepository permissionRepository;
	
	@Override
	public Role postConvertToDo(RoleInputArgs i, Role d) {
		return postUpdate(i, d);
	}

	@Override
	public Role postUpdate(RoleInputArgs i, Role d) {
		d.setName(i.getName());
		d.setDescription(i.getDescription());
		List<String> permissionIds = i.getPermIds();
		if (permissionIds != null) {
			Set<Permission> permissions = new HashSet<>();
			for (String permissionId : permissionIds) {
				Permission permission = permissionRepository.findOne(permissionId);
				permissions.add(permission);
			}
			d.setPerms(permissions);
		} else {
			d.setPerms(null);
		}
		return d;
	}

}
